<?php
/**
 * Created by PhpStorm.
 * User: wb-liuyuguang
 * Date: 14-5-19
 * Time: 上午10:41
 */
session_start();
require('website.php');
unset($_SESSION['conf']);
if( !isset($_SESSION['conf']) ){
    if( isset($_POST['username']) && isset($_POST['password']) ){
        $host = new GitWebsite();
        if( $host->login("https://git.oschina.net/login", $_POST['username'], $_POST['password']) !== false ){
            $txt = $host->get('http://git.oschina.net/benemind/GitDeployerConf/raw/master/rules.csv');
            if($txt !== false ){
                $lines = str_getcsv($txt);
                $csv = csvstring_to_array($txt);
                $_SESSION['conf'] = $csv;
            }
        }

    }
}
if( !isset($_SESSION['conf']) ){
    require('login.php');
    return;
}
require('list.php');


function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
    // @author: Klemen Nagode
    $array = array();
    $size = strlen($string);
    $columnIndex = 0;
    $rowIndex = 0;
    $fieldValue="";
    $isEnclosured = false;
    for($i=0; $i<$size;$i++) {

        $char = $string{$i};
        $addChar = "";

        if($isEnclosured) {
            if($char==$enclosureChar) {

                if($i+1<$size && $string{$i+1}==$enclosureChar){
                    // escaped char
                    $addChar=$char;
                    $i++; // dont check next char
                }else{
                    $isEnclosured = false;
                }
            }else {
                $addChar=$char;
            }
        }else {
            if($char==$enclosureChar) {
                $isEnclosured = true;
            }else {

                if($char==$separatorChar) {

                    $array[$rowIndex][$columnIndex] = $fieldValue;
                    $fieldValue="";

                    $columnIndex++;
                }elseif($char==$newlineChar) {
                    echo $char;
                    $array[$rowIndex][$columnIndex] = $fieldValue;
                    $fieldValue="";
                    $columnIndex=0;
                    $rowIndex++;
                }else {
                    $addChar=$char;
                }
            }
        }
        if($addChar!=""){
            $fieldValue.=$addChar;

        }
    }

    if($fieldValue) { // save last field
        $array[$rowIndex][$columnIndex] = $fieldValue;
    }
    return $array;
}
?>
